<?php
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/**
 * Represents the response items that get handed back as json within the
 * DataResponse
 */
class response_item {
	public $error;
	public $error_message;
	public $response;

	public function __construct($error = null, $error_message = null, $response = null) {
		$this->error = $error;
		$this->error_message = $error_message;
		$this->response = $this->trim_response($response);
		if ($this->error === null && $this->error_message === null) {
			// trim null values of self too
			unset($this->error);
			unset($this->error_message);
		}
	}

	/**
	 * the json_encode function does not trim null values,
	 * so we do this manually
	 *
	 * @param mixed $object
	 */
	private function trim_response(&$object) {
		if (is_array($object)) {
			foreach ($object as $key => $val) {
				// binary compare, otherwise false == 0 == null too
				if ($val === null) {
					unset($object[$key]);
				} elseif (is_array($val) || is_object($val)) {
					$object[$key] = $this->trim_response($val);
				}
			}
		} elseif (is_object($object)) {
			$vars = get_object_vars($object);
			foreach ($vars as $key => $val) {
				if ($val === null) {
					unset($object->$key);
				} elseif (is_array($val) || is_object($val)) {
					$object->$key = $this->trim_response($val);
				}
			}
		}
		return $object;
	}

	public function get_error() {
		return isset($this->error) ? $this->error : null;
	}

	public function set_error($error) {
		$this->error = $error;
	}

	public function get_error_message() {
		return $this->error_message;
	}

	public function set_error_message($error_message) {
		$this->error_message = $error_message;
	}

	public function get_response() {
		return $this->response;
	}

	public function set_response($response) {
		$this->response = $response;
	}
}
